import mysql from 'mysql'
import dbConfig from '../config/dbConfig.js'

const dbPool = {}

const handleConnection = function (error, connect, sql, params, callback) {
  if(error) {
    callback(err, null, null)
    return
  }
  const handleResult = function(err, vals, fields) {
    // 释放连接
    connect.release();
    // 事件驱动回调
    callback(err, vals, fields);
  }
  connect.query(sql, params, handleResult)
}

// 获取数据库配置信息 新建连接池
const pool = mysql.createPool(dbConfig)

// 查、删、改、插入、也可执行存储过程
dbPool.queryPool = function (sql, params, callback) {
  pool.getConnection((error, connect) => handleConnection(error, connect, sql, params, callback))
}

export default dbPool